package cn.qyd.aqs;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 邱运铎
 * @date 2024-03-18 23:12
 */
public class ReentrantLockDemo {
    public ReentrantLock reentrantLock = new ReentrantLock();
    public int count = 0;

    public void increment() {
        reentrantLock.lock();
        try {
            count++;
            System.out.println("增量 " + Thread.currentThread().getName() + " : " + count);
        } finally {
            reentrantLock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo demo = new ReentrantLockDemo();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++)
                demo.increment();
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终count的值为： " + demo.count);
    }


}
